<?php
/**
 * Created by PhpStorm.
 * User: liuyu
 * Date: 2018/11/19
 * Time: 11:19
 */

namespace App\Http\Controllers\Api\v1\Fortune;

use App\Http\Controllers\Api\BaseController;
use App\Tools\Astrolog\FortunesChange;
use App\Models\Api\AppLogicVersion;
use App\Models\Api\SystemLogicVersion;
use App\Models\Api\AwardUser;
use App\Models\Api\Orders;
use App\Models\Api\Recode;
use Illuminate\Http\Request;

use Cache;

class FortuneForMonthController extends BaseController
{
    protected $orders_model;
    protected $award_user_model;
    protected $month_id;
    protected $recodeModel;

    public function __construct()
    {
        //parent::__construct();

        $this->month_id = config('app.month_id');
        $this->orders_model = new Orders();
        $this->award_user_model = new AwardUser();
        $this->recodeModel = new Recode();
    }

    /**
     * @return \think\response\Json
     * @throws \app\common\lib\exception\ApiException
     */
    public function index(Request $request)
    {
        if (!$request->isMethod('get')) {
            return show(config('code.error'), '未知操作', [], 403);
        }

        $uid = $request->uid;
        $rid = $request->input('rid');
        $year = $request->input('year');
        $month = $request->input('month');
        //当前查看的时间
        $now_time = strtotime($year . '-' . $month);
        //日历显示时间范围
        $range_start = config('fortune.fortune_time_range')['month']['start'];
        $range_end = config('fortune.fortune_time_range')['month']['end'];

        //解锁状态
        $unlock_status = 0;
//          if(Cache::has('fortune_months_' . $uid.'_'.$rid,$year, 86400 * 365) && in_array($uid, config('vip'))){
//              $start_time = date('Y-m', strtotime('2023-01'));
//              $end_time = date('Y-m', strtotime('-1 months', strtotime('2023-12-31')));
//              $unlock_vip_time = prDates(['start' => $start_time, 'end' => $end_time, 'type' => '2']);
//              $unlock_vip_times[] = $unlock_vip_time;
//              $unlock_status = 2;
//              if ($unlock_vip_times) {
//                 foreach ($unlock_vip_times as $k => $v) {
//                     foreach ($v as $vv) {
//                         $vip_time_range[] = $vv;
//                     }
//                 }
//             }
//          } else {
//       //TODO  是否为VIP用户判断，若为VIP用户，全部解锁且加入计算队列
//         if (in_array($uid, config('vip')))
//         {
//              $start_time = date('Y-m', strtotime('2023-01'));
//              $end_time = date('Y-m', strtotime('-1 months', strtotime('2023-12-31')));
//              $unlock_vip_time = prDates(['start' => $start_time, 'end' => $end_time, 'type' => '2']);
//             //将运势加入队列运算
//             $recode_info [] = (new Recode())->getRecode(['uid' => $uid, 'id' => $rid]);
//             //var_dump($recode_info);die;
//             // TODO 判断是否已经加入队列/已经计算完毕
//             // 运势队列消费时需要的数据
//             $jobData = [
//                 'recode' =>$recode_info,
//                 'start_time' => $unlock_vip_time,
//                 'type' => 'month',
//             ];
//              $unlock_vip_times[] = $unlock_vip_time;
// // //            // 运势队列相关配置
//              $fortune_job_setting = config('queue');
// //             //var_dump($recode_info);die;
// // //            // VIP 用户加入立即计算队列中 否则 $fortune_job_setting['delay']
//              queuePush($fortune_job_setting['fortune_task'],$jobData,$fortune_job_setting['fortune_queue'],0);
//  //       VIP 用户更改为已解锁
//             $unlock_status = 1;
//             $unlock_status = 2;
//             Cache::set('fortune_months_'. $uid.'_'.$rid, $year, 86400 * 365);
//              if ($unlock_vip_times) {
//                 foreach ($unlock_vip_times as $k => $v) {
//                     foreach ($v as $vv) {
//                         $vip_time_range[] = $vv;
//                     }
//                 }
//             }
//         }
//     }

        //获取档案购买的订单
        $orders = $this->orders_model->fortune_orders(['uid' => $uid, 'rid' => $rid, 'type' => 2]);

        //购买订单解锁时间
        $unlock_time = [];
        $order_time = [];
        $unlock_time_range = [];

        if ($orders && !empty($orders)) {
            //获取档案解锁的信息
            foreach ($orders as $k => $v) {
                if ($v['type'] == 2) {
                    $extend = json_decode($v['extend'], true);
                    if (isset($extend['expire_time']) && $extend['expire_time']) {
                        $v['expire_time'] = $extend['expire_time'];
                    }
                    $start_time = date('Y-n', $v['time']);
                    $end_time = date('Y-n', strtotime('-1 months',strtotime($v['expire_time'], $v['time'])));

                    $unlock_time['start_time'] = $start_time;
                    $unlock_time['end_time'] = $end_time;

                    $order_time[] = prDates(['start' => $unlock_time['start_time'], 'end' => $unlock_time['end_time'], 'type' => 2]);

                    if (strtotime($start_time) <= $now_time && $now_time <= strtotime($end_time)) {
                        $unlock_status = 1;

                        if ($v['status'] == 4) {
                            $unlock_status = 2;
                        }

                    }
                }
            }

            foreach ($order_time as $k => $v) {
                foreach ($v as $vv) {
                    $unlock_time_range[] = $vv;
                }
            }
        }

        // 获取当前用户的档案id
        $selfId = $this->recodeModel->getSelfRecode(['uid' => $request->uid]);
        //获取中奖纪录
        $aorders = $this->award_user_model->get_award_fortune(['uid' => $request->uid, 'rid' => $rid, 'type' => 3,'self_id'=>$selfId]);

        //中奖解锁时间
        $award_time = [];
        $unlock_award_times = [];
        $award_time_range = [];
        $vip_time_range =[];

        if ($aorders && !empty($aorders)) {
            // 获取当前用户中奖解锁的时间
            $date = date('Y-n', $now_time);
            //获取用户中奖的信息
            foreach ($aorders as $k => $v) {
                $extend = json_decode($v['extend'], true);

                if (in_array($v['aid'], $this->month_id)) {
                    $start_time = date('Y-n', $extend['award_time']);
                    $end_time = date('Y-n', strtotime('-1 months',strtotime($v['expire_time'], $extend['award_time'])));

                    $award_time['start_time'] = $start_time;
                    $award_time['end_time'] = $end_time;
                    $unlock_award_time = prDates(['start' => $award_time['start_time'], 'end' => $award_time['end_time'], 'type' => 2]);
                    $unlock_award_times[] = $unlock_award_time;

                    if (in_array($date, $unlock_award_time) && $v['status'] == 1) {
                        $unlock_status = 2;
                    } elseif (in_array($date, $unlock_award_time)) {
                        $unlock_status = 1;
                    }

                }
            }

            if ($unlock_award_times) {
                foreach ($unlock_award_times as $k => $v) {
                    foreach ($v as $vv) {
                        $award_time_range[] = $vv;
                    }
                }
            }
        }

        //合并时间
        $time_range = array_merge($unlock_time_range, $award_time_range,$vip_time_range);
        //时间去重
        $time_range = array_unique($time_range);
        //重新排序
        asort($time_range);
        //重新索引
        $time_range = array_values($time_range);
//        }


        //统计订单人数
//        $order_people_num = $this->orders_model->Unlock_people_num(['type' => 2]);
        $fortune_base_num = $this->orders_model->fortune_base(['type' => 1]);

        if ($unlock_status == 0) {
            $unlock_tips = [
                'title' => '月运解锁',
                'content' => '解锁当前运势,可查看你本月会发生什么,并提前七天得到预警,得知对应的方法和建议。',
            ];
        } elseif ($unlock_status == 1) {
            $unlock_tips = [
                'title' => '月运解锁等待中...',
                'content' => '由于月运的计算量较大,准了将在24小时内为您献上您所需要的月运。
小伙伴们耐心等待哦~',
            ];
        } elseif ($unlock_status == 3) {
            $unlock_tips = [
                'title' => '月运更新等待中...',
                'content' => '由于月运正在重新计算中,准了将在24小时内为您献上您所需要的月运。',
            ];
        } else {
            $unlock_tips = [
                'title' => '你是vip用户',
                'content' => '欢迎你使用',
                ];
        }

        //更新逻辑数据定义
        $update_logic = [
            'title' => '',
            'content' => '',
            'status' => 0
        ];
        //用户计算成功后获取运势信息并查询逻辑版本信息
        if ($unlock_status === 2) {
            $map = ['uid' => $uid, 'id' => $rid];
            //获取档案信息
            $recode_info = $this->recodeModel->getRecode($map);

            //获取运势信息
            $fortune = (new FortunesChange())->init($recode_info, $year . '-' . str_pad($month, 2, '0', STR_PAD_LEFT));

            //获取当前最新版本逻辑信息
            $SystemLogicModel = new SystemLogicVersion();
            $logic_data = $SystemLogicModel->getVersion(['type' => 2]);
            //获取当前档案逻辑版本号
            $AppLogicModel = new AppLogicVersion();
            $user_logic = $AppLogicModel->getVersion(['rid' => $rid, 'type' => 2, 'time' => date('Y-m', $now_time)]);

            if ($user_logic) {
                //若查看的时间版本号不是最新,提示更新
                if ($logic_data['version'] && $user_logic < $logic_data['version']) {
                    $update_logic = [
                        'title' => $logic_data['title'],
                        'content' => $logic_data['content'],
                        'status' => 1,
                    ];
                }
            } elseif (!$user_logic) {
                $update_logic = [
                    'title' => $logic_data['title'],
                    'content' => $logic_data['content'],
                    'status' => 1,
                ];
            }
        } else {
            $fortune = [
                'underway_fortune' => [],
                'predicted_fortune' => [],
                'completed_fortune' => [],
            ];
        }

        $data = [
//            'self_rid' => intval($recode_info['id']),
            'time' => $time_range,
            'underway_fortune' => $fortune['underway_fortune'],
            'predicted_fortune' => $fortune['predicted_fortune'],
            'completed_fortune' => $fortune['completed_fortune'],
            'unlock_num' => intval($fortune_base_num),
            'unlock_status' => $unlock_status,
            'time_range' => [
                'start_time' => $range_start,
                'end_time' => $range_end,
            ],
            'update_logic' => $update_logic,
            'unlock_tips' => $unlock_tips,
        ];

        // 活动开关，默认关闭
        //$config = config('active.fortune_active');
        $config = '';
        $data['active_switch']=[
            'day_active'=>[
                'is_open'=>false,
                'icon'=>'',
                'banner'=>'',
                'target'=>'link',
                'link'=>'/web/fortune_year/active_details',//大礼包h5
            ],
            'month_active'=>[
                'is_open'=>false,
                'icon'=>'',
                'banner'=>'',
                'target'=>'link',
                'link'=>'/web/fortune_year/active_details',//大礼包h5
            ],
            'year_active'=>[
                'is_open'=>false,
                'icon'=>'',
                'banner'=>'',
                'target'=>'link',
                'link'=>'/web/fortune_year/active_details',//大礼包h5
            ]

        ];
        //若未解锁并在活动时间内，开启
        if (checktime() && $unlock_status == 0)
        {
            $data['active_switch']['day_active']['is_open']=false;
            $data['active_switch']['month_active']['is_open']=true;
            $data['active_switch']['year_active']['is_open']=true;
        }

        return show(config('code.success'), '加载成功', $data);
    }
}
